<template>
  <div>
      <n-auto-complete
          v-model:value= "row.prompt"
          :append= "true"
          :get-show= "getPrompts"
          :options= "options"
          placeholder= "请输入"
          :render-label= "renderLabel"
          @focus= "queryEnable = true"
          @blur= "queryEnable = false"
          @update:value="(value:string)=> updateValue(value)"
          @select= "optionSelect"
      >
        <template
            #default="{ handleInput, handleBlur, handleFocus, value: slotValue }"
        >
          <n-input
              type="textarea"
              style="height: 220px"
              :value="slotValue"
              placeholder="请输入提示词"
              @input="handleInput"
              @focus="handleFocus"
              @blur="handleBlur"
          />
        </template>
    </n-auto-complete>
  </div>
 </template>

<script setup lang="ts">
//@ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import { NTag} from "naive-ui";
import {computed, h, ref, watch} from "vue";
import {useMessage } from 'naive-ui';
import {tagCategoryController} from "@/api/controller/tagcategory/tagCategoryController";
import {storyBoardController} from "@/api/controller/story/storyBoard.api";

const isSelectingOption = ref(false)
const autoCompletion = ref([])
const message = useMessage()
const loading = ref(false)
const prompt = ref('')
const queryEnable = ref(false)
const selectedValue = ref('')
const searchTagValue = ref('')


const props = defineProps({
    row: {
        type: Object,
        default: () => {
            return {}
        }
    },
    weightOpen: {
      type: Boolean,
      default: false
    }
})

watch(() => props.row.prompt, (newVal) => {
  if (props.row.prompt.endsWith("，")) {
    props.row.prompt = props.row.prompt.substring(0, props.row.prompt.length - 1) + ","
  }
})

const renderLabel = (option: any) => {
  return [
    option.label as string,
    ' ',
    h(NTag, {size: 'small', type: 'info'}, {default: () => option.category})
  ]
}

const tags = computed(() => {
  if (props.row.prompt === '' || props.row.prompt === null) {
    return []
  }
   return getTags(props.row.prompt)
})

const getTags = (promptTags:any) => {
  const splitTags = promptTags.split(',')
  for (let i = 0; i < splitTags.length; i++) {
    if (splitTags[i] === '') {
      splitTags.splice(i, 1)
    }
  }
  return splitTags
}

const options = computed(() => {
  return autoCompletion.value.map((item:any) => {
    return {
      label: item.zh,
      value: item.en,
      category: item.categoryName
    }
  })
})


const getPrompts = async (value:string) => {
  autoCompletion.value = []
  if (queryEnable.value === false) {
    return false
  }
  searchTagValue.value = searchValue(value)
  if (searchTagValue.value === ''){
    return false
  }
  autoCompletion.value = []
  const data ={
    categoryCode: '03',
    search : searchTagValue.value
  }
  const res = await tagCategoryController.autoCompletion(data)
  if (res.code == 200) {
    autoCompletion.value = res.data
    return true
  }else {
    return false
  }
}


const searchValue = (typeValue:string) =>{
  let result = ''; // 使用不同的变量名以避免冲突
  const markIndex = typeValue.lastIndexOf(",")
  if (markIndex === -1) {
    // 如果没有找到逗号或者字符串以逗号结尾，使用整个字符串
    result = typeValue;
  } else {
    // 否则，截取逗号后面的内容
    result = typeValue.substring(markIndex + 1);
  }
  return result;
}


/***
 * 按下回车键,分镜内新增句子
 * @param item
 * @param event
 */
const handlerEnter = (event: any) => {
  if (isSelectingOption.value) {
    return
  }
  if (prompt.value === '') {
    return
  }
  props.row.prompt = props.row.prompt + ',' + prompt.value
  prompt.value = ''
  updateBoard()
}


const getWeight = (data:string) => {
  if (data.startsWith("(") && data.endsWith(")") && data.indexOf(":") > 0) {
    data = data.substring(1, data.length - 1)
    return data.split(":")
  }else {
    return [data, 1]
  }
}


const addWeight = (data:any) => {
  let tags = getTags(props.row.prompt)
  for (let i = 0; i < tags.length; i++) {
    for (let i = 0; i < tags.length; i++) {
      if (tags[i] == data) {
        const tagWithWeight = getWeight(data)
        let thisTag = tagWithWeight[0]
        let thisWeight = Number(tagWithWeight[1])
        if (thisWeight >= 1.9){
          return
        }
        let weight = (thisWeight + Number(0.1)).toFixed(1)
        console.log(weight)
        let newTag = '(' + thisTag + ':' + weight + ')'
        if (Number(weight) == 1){
          newTag = thisTag
        }
        tags[i] = newTag
      }
    }
  }
  props.row.prompt = tags.join(',')
  updateBoard()
}


const removeWeight = (data:any)=>{
  let tags = getTags(props.row.prompt)
  for (let i = 0; i < tags.length; i++) {
    for (let i = 0; i < tags.length; i++) {
      if (tags[i] == data) {
        const tagWithWeight = getWeight(data)
        let thisTag = tagWithWeight[0]
        let thisWeight = Number(tagWithWeight[1])
        if (thisWeight <= 0.5){
          return
        }
        let weight = (thisWeight - Number(0.1)).toFixed(1)
        let newTag = '(' + thisTag + ':' + weight + ')'
        if (Number(weight) == 1){
          newTag = thisTag
        }
        tags[i] = newTag
      }
    }
  }
  props.row.prompt = tags.join(',')
  updateBoard()
}


const updateBoard = () => {
  const param = {...props.row}
  delete param.characterList
  storyBoardController.addOrUpdateBoard(param).then(res => {
    if (res.code !== 200) {
      message.error(res.msg)
    }
  })
}

const deletePrompt = (event:any,tag:any)=>{
  console.log(tag)
  let tags = getTags(props.row.prompt)
  for (let i = 0; i < tags.length; i++) {
    if (tags[i] == tag) {
      tags.splice(i, 1)
    }
  }
  props.row.prompt = tags.join(',')
  updateBoard()
}

const updateValue = (value: string) => {
  props.row.prompt = value.replace(/，/g, ',');

  if ( value == '' || value == null || value=='null' || searchTagValue.value == '' || selectedValue.value == '') {
    props.row.prompt = props.row.prompt.replaceAll("null", "")
    selectedValue.value = ''
    searchTagValue.value = ''
    updateBoard()
    return
  }

  const markIndex = value.lastIndexOf(",")
  if(markIndex == -1){
    props.row.prompt = selectedValue.value
  }else {
    const lastValue = value.substring(0,markIndex)
    props.row.prompt = lastValue + ',' + selectedValue.value
  }
  selectedValue.value = ''
  searchTagValue.value = ''
  updateBoard()
}

const optionSelect = (value: string) => {
  selectedValue.value = value
}

</script>

<style>
</style>
